﻿namespace ChinaUnicom
{
    using ChinaUnicom.Web;
    using System.Net;
    using System;

    public sealed class Authentication
    {
        static object locker = new object();

        string value;
        public const string Key = "unicomMobileNum";

        private Authentication()
        {
            value = ApplicationSettings.Settings[Key];
            Signed = false;
        }

        static Authentication current;
        public static Authentication Current
        {
            get
            {
                if (current == null)
                {
                    lock (locker)
                    {
                        current = new Authentication();
                    }
                }

                return current;
            }
        }

        public Cookie Cookie
        {
            get
            {
                if (string.IsNullOrEmpty(value))
                {
                    return null;
                }

                return new Cookie(Key, value, "/") { Expires = DateTime.Now.AddMinutes(60), Version = 1 };
            }
        }

        public void Register(string cookie)
        {
            if (string.IsNullOrEmpty(cookie))
            {
                return;
            }

            this.value = cookie;
            ApplicationSettings.Settings[Key] = cookie;
        }

        /// <summary>
        /// 表示已经取得授权，但是没有登录，需要 Call IOperation.AutoLogin()
        /// </summary>
        public bool Authorized
        {
            get { return Cookie != null; }
        }

        public void Logout()
        {
            Factory.Operation.Logout();
            value = string.Empty;
            Signed = false;
            ApplicationSettings.Settings[Key] = string.Empty;
        }

        /// <summary>
        /// 表示已经登录成功
        /// </summary>
        public bool Signed { get; set; }
    }
}
